package com.joyxy.easy.gui;

import com.joyxy.easy.entity.OtherConfig;
import com.joyxy.easy.entity.SkillConfig;
import com.joyxy.easy.entity.StatusConfig;
import com.joyxy.easy.entity.WindowContext;
import com.joyxy.easy.manger.WindowManager;
import com.joyxy.easy.monitor.AutomationRunner;
import com.joyxy.easy.monitor.StatusMonitor;
import com.joyxy.easy.service.SpiderService;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class BasicSettingPanel extends JPanel {
    private final long hwnd;

    private final List<JCheckBox> buffCheckBoxes = new ArrayList<>();
    private final List<JTextField> skillKeyFields = new ArrayList<>();
    private final List<JTextField> intervalFields = new ArrayList<>();
    private final List<JComboBox<String>> unitCombos = new ArrayList<>();
    private final List<JCheckBox> enableChecks = new ArrayList<>();

    private final JCheckBox hpCheckBox = new JCheckBox("", true);
    private final JTextField hpThresholdField = new JTextField("1200", 5);
    private final JTextField hpKeyField = new JTextField("s", 5);

    private final JCheckBox mpCheckBox = new JCheckBox("", true);
    private final JTextField mpThresholdField = new JTextField("1500", 5);
    private final JTextField mpKeyField = new JTextField("E", 5);

    private final JCheckBox debuffCheckBox = new JCheckBox("", true);
    private final JTextField debuffThresholdField = new JTextField("5", 5);
    private final JTextField debuffKeyField = new JTextField("r", 5);

    private final JCheckBox lockAddress = new JCheckBox("锁定坐标",true);
    private final JCheckBox lockFace = new JCheckBox("锁定方向",true);
    private final JCheckBox pickUp = new JCheckBox("捡取",true);

    private final JButton startBtn = new JButton("开始");
    private final JButton stopBtn = new JButton("停止");
    private final JButton spiderBtn = new JButton("卖垃圾");
    private final JButton goToSpiderBtn = new JButton("去蜘蛛并开始");

    private final JTextField ZZFloor = new JTextField("4", 5);
    private final JTextField TDFKey = new JTextField("q", 5);

    private final JLabel spiderTime = new JLabel("持续时间: -");

    private SpiderService spiderService;

    public BasicSettingPanel(long hwnd) {
        this.hwnd = hwnd;
        initUI();
        this.spiderService = new SpiderService(hwnd);
    }

    private void initUI() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建主面板（包含技能循环和状态监控）
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        // 添加技能循环面板
        mainPanel.add(createSkillCyclePanel());
        mainPanel.add(Box.createVerticalStrut(20)); // 间距

        // 添加状态监控面板
        mainPanel.add(createStatusMonitorPanel());
        mainPanel.add(Box.createVerticalGlue()); // 占位

        // 创建滚动面板
        JScrollPane scrollPane = new JScrollPane(mainPanel);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        add(scrollPane, BorderLayout.CENTER);

        // 添加底部按钮面板
        add(createActionButtonsPanel(), BorderLayout.SOUTH);
    }

    private JPanel createSkillCyclePanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(BorderFactory.createTitledBorder("技能循环设置"));

        // 表头
        JPanel header = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
        header.add(new JLabel("buff技能"));
        header.add(new JLabel("技能键"));
        header.add(new JLabel("间隔时间"));
        header.add(new JLabel("单位"));
        header.add(new JLabel("启用"));
        panel.add(header);
        //暂时先默认法师配置
        for (int i = 0; i < 4; i++) {
            JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 6));
            if (i == 1||i==0||i==2) {
                JCheckBox buffCheck = new JCheckBox("", true);
                buffCheckBoxes.add(buffCheck);
                row.add(buffCheck);
            }else{
                JCheckBox buffCheck = new JCheckBox("", false);
                buffCheckBoxes.add(buffCheck);
                row.add(buffCheck);
            }
            String text = "";
            String time = "5";
            if (i == 0) {
                text = "d";
                time = "177";
            }
            if(i==1){
                text = "f";
                time = "300";
            }
            if(i==2){
                text = "w";
                time = "200";
            }
            if(i==3){
                text = "a";
                time = "5";
            }
            JTextField keyField = new JTextField(5);
            keyField.setText(text);
            skillKeyFields.add(keyField);
            row.add(keyField);

            JTextField intervalField = new JTextField(5);
            intervalField.setText(time);
            intervalFields.add(intervalField);
            row.add(intervalField);

            JComboBox<String> unitCombo = new JComboBox<>(new String[]{"秒", "分"});
            unitCombos.add(unitCombo);
            row.add(unitCombo);

            JCheckBox enableCheck = new JCheckBox("", true);
            enableChecks.add(enableCheck);
            row.add(enableCheck);

            panel.add(row);
        }
        // 8行技能设置
        for (int i = 4; i < 8; i++) {
            JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 6));

            JCheckBox buffCheck = new JCheckBox("", false);
            buffCheckBoxes.add(buffCheck);
            row.add(buffCheck);

            JTextField keyField = new JTextField(5);
            skillKeyFields.add(keyField);
            row.add(keyField);

            JTextField intervalField = new JTextField(5);
            intervalFields.add(intervalField);
            row.add(intervalField);

            JComboBox<String> unitCombo = new JComboBox<>(new String[]{"秒", "分"});
            unitCombos.add(unitCombo);
            row.add(unitCombo);

            JCheckBox enableCheck = new JCheckBox("", true);
            enableChecks.add(enableCheck);
            row.add(enableCheck);

            panel.add(row);
        }

        return panel;
    }

    private JPanel createStatusMonitorPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(BorderFactory.createTitledBorder("状态监控设置"));

        // 血量监控
        panel.add(createMonitorRow("血量低于:", hpThresholdField, "时按下:", hpKeyField, hpCheckBox));
        panel.add(Box.createVerticalStrut(5));

        // 魔法监控
        panel.add(createMonitorRow("魔法低于:", mpThresholdField, "时按下:", mpKeyField, mpCheckBox));
        panel.add(Box.createVerticalStrut(5));

        // debuff 监控
        panel.add(createMonitorRow("蜘蛛buff高于:", debuffThresholdField, "时按下:", debuffKeyField, debuffCheckBox));
        panel.add(Box.createVerticalStrut(5));

        JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
        row.add(new JLabel("蜘蛛层数"));
        row.add(ZZFloor);
        panel.add(row);
        panel.add(Box.createVerticalStrut(5));

        JPanel rowTdf = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
        rowTdf.add(new JLabel("土地符键位"));
        rowTdf.add(TDFKey);
        panel.add(rowTdf);
        panel.add(Box.createVerticalStrut(5));
        return panel;

    }

    private JPanel createMonitorRow(String label1, JComponent field1, String label2, JComponent field2, JComponent checkBox) {
        JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
        row.add(checkBox);
        row.add(new JLabel(label1));
        row.add(field1);
        row.add(new JLabel(label2));
        row.add(field2);
        return row;
    }

    private JPanel createActionButtonsPanel() {
        JPanel panel = new JPanel(new GridLayout(2, 1, 5, 5));
        panel.setBorder(BorderFactory.createTitledBorder("快捷操作"));

        // 第一行：功能按钮
        JPanel functionPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        functionPanel.add(lockAddress);
        functionPanel.add(lockFace);
        functionPanel.add(pickUp);
        // 第二行：开始/停止按钮
        JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        startBtn.setPreferredSize(new Dimension(100, 40));
        stopBtn.setPreferredSize(new Dimension(100, 40));
        spiderBtn.setPreferredSize(new Dimension(100, 40));
        goToSpiderBtn.setPreferredSize(new Dimension(200, 40));



        startBtn.addActionListener(e -> startAutomation());
        stopBtn.addActionListener(e -> stopAutomation());
        spiderBtn.addActionListener(e -> startSpiderSell());
        goToSpiderBtn.addActionListener(e -> goToSpiderAndStart());
        controlPanel.add(spiderBtn);
        controlPanel.add(startBtn);
        controlPanel.add(stopBtn);
        controlPanel.add(goToSpiderBtn);
        controlPanel.add(spiderTime);
        // 定时更新UI
        new Timer(200, e -> updateStats()).start();
        // 添加到主面板
        panel.add(functionPanel);
        panel.add(controlPanel);

        return panel;
    }

    private void updateStats() {
        WindowContext context = WindowManager.getContext(hwnd);
        AutomationRunner automationRunner = context.getAutomationRunner();
        if(automationRunner != null) {
            spiderTime.setText(automationRunner.getTime());
        }
    }

    private void goToSpiderAndStart() {
        boolean sell = WindowManager.getContext(hwnd).getMonitor().isSell();
        if (!sell) {
            new Thread(() -> {
                spiderService.autoSell(Integer.parseInt(ZZFloor.getText().trim().toLowerCase()),TDFKey.getText().trim().toLowerCase(),false);
                //重新开始放技能
                startAutomation();
                AutomationRunner automationRunner = WindowManager.getContext(hwnd).getAutomationRunner();
                automationRunner.setLockX( WindowManager.getContext(hwnd).getMonitor().getX());
            }).start();
        }
    }

    private void startSpiderSell() {
        boolean sell = WindowManager.getContext(hwnd).getMonitor().isSell();
        if (!sell) {
            new Thread(() -> {
                spiderService.autoSell(Integer.parseInt(ZZFloor.getText().trim().toLowerCase()),TDFKey.getText().trim().toLowerCase(),true);
                //重新开始放技能
                AutomationRunner automationRunner = WindowManager.getContext(hwnd).getAutomationRunner();
                automationRunner.startSkill();
                automationRunner.setLockX( WindowManager.getContext(hwnd).getMonitor().getX());
            }).start();
        }
    }


    private void startAutomation() {
        AutomationRunner automationRunner = WindowManager.getContext(hwnd).getAutomationRunner();
        if (automationRunner != null && automationRunner.isRunning()) {
            JOptionPane.showMessageDialog(this, "已在运行中", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        StatusMonitor monitor = WindowManager.getContext(hwnd).getMonitor();
        // 收集所有配置
        List<SkillConfig> skillConfigs = new ArrayList<>();
        for (int i = 0; i < skillKeyFields.size(); i++) {
            boolean buff = buffCheckBoxes.get(i).isSelected();
            String key = skillKeyFields.get(i).getText().trim();
            String intervalText = intervalFields.get(i).getText().trim();
            String unit = (String) unitCombos.get(i).getSelectedItem();
            boolean enabled = enableChecks.get(i).isSelected();

            if (!key.isEmpty() && !intervalText.isEmpty() && enabled) {
                skillConfigs.add(new SkillConfig(buff, key, intervalText, unit));
            }
        }

        StatusConfig statusConfig = new StatusConfig(
                hpCheckBox.isSelected(),
                hpThresholdField.getText().trim().toLowerCase(),
                hpKeyField.getText().trim().toLowerCase(),
                mpCheckBox.isSelected(),
                mpThresholdField.getText().trim().toLowerCase(),
                mpKeyField.getText().trim().toLowerCase(),
                debuffCheckBox.isSelected(),
                debuffThresholdField.getText().trim().toLowerCase(),
                debuffKeyField.getText().trim().toLowerCase(),
                ZZFloor.getText().trim().toLowerCase()
        );
        OtherConfig otherConfig = new OtherConfig(
                lockAddress.isSelected(),
                monitor.getX(),
                lockFace.isSelected(),
                monitor.getFace(),
                pickUp.isSelected()
        );
        automationRunner = new AutomationRunner(hwnd, skillConfigs, statusConfig, otherConfig);
        WindowManager.getContext(hwnd).setAutomationRunner(automationRunner);
    }

    private void stopAutomation() {
        AutomationRunner automationRunner = WindowManager.getContext(hwnd).getAutomationRunner();
        if (automationRunner != null && automationRunner.isRunning()) {
            automationRunner.stop();
        }
    }

}